package foxesandrabbits.species;

import java.util.Iterator;
import java.util.List;
import java.util.Random;

import foxesandrabbits.field.Field;
import foxesandrabbits.field.Location;
import foxesandrabbits.random.Randomizer;

public abstract class Killer extends AliveObject{

	protected int foodLevel;
	protected int FOOD_VALUE;
	
	public Killer(boolean randomAge, Field field, Location location) {
		super(randomAge, field, location);
		if(!randomAge) 
		{
            age = 0;
            foodLevel = FOOD_VALUE;
        }
	}
	
    /**
     * Make this fox more hungry. This could result in the fox's death.
     */
    private void incrementHunger()
    {
        foodLevel--;
        if(foodLevel <= 0) {
            setDead();
        }
    }
    
    /**
     * Look for rabbits adjacent to the current location.
     * Only the first live rabbit is eaten.
     * @return Where food was found, or null if it wasn't.
     */
    private Location findFood()
    {
        Field field = getField();
        List<Location> adjacent = field.adjacentLocations(getLocation());
        Iterator<Location> it = adjacent.iterator();
        while(it.hasNext()) {
            Location where = it.next();
            Object animal = field.getObjectAt(where);
            if(animal instanceof Rabbit) {
                Rabbit rabbit = (Rabbit) animal;
                if(rabbit.isAlive()) { 
                    rabbit.setDead();
                    foodLevel = FOOD_VALUE;
                    return where;
                }
            }
        }
        return null;
    }
    /**
     * This is what the fox does most of the time: it hunts for
     * rabbits. In the process, it might breed, die of hunger,
     * or die of old age.
     * @param newFoxes A list to return newly born foxes.
     */
	public void act(List<AliveObject> newAnimals)
	{
		super.act(newAnimals);
		incrementHunger();
		if(isAlive()) {
			Location newLocation = findFood();
			if(newLocation == null) { 
				// No food found - try to move to a free location.
                newLocation = getField().freeAdjacentLocation(getLocation());
            }
            // See if it was possible to move.
            if(newLocation != null) {
                setLocation(newLocation);
            }
            else {
                // Overcrowding.
                setDead();
            }
		}
	}
	
}
